package com.huizluo.module1;

//自动扩容数据
public class MyArray {
    private Object[] data;
    private int cap;
    private int length;

    public MyArray(int cap) {
        this.cap = cap;//数组最大容量
        this.length = 0;//数组当前包含数据数量
        this.data = new Object[cap];//存放数据
    }

    public void push(Object object){
        float o = (float)this.length / this.cap;
        //如果当前使用量 / 总量 > 0.8
        if (o >= 0.8){
            int c = (int)(this.cap * 1.5);
            Object[] tmp = new Object[c];//初始化一个零时数组
            //数据从老数组迁移到零时数组
            for(int i=0;i<this.length;i++){
                tmp[i] = this.data[i];
            }
            //将新数据插入零时数组
            tmp[this.length] = object;

            //将零时数组赋值给原始数据
            this.data = tmp;
            this.length = this.length + 1;
            this.cap = c;
        }else{
            this.data[this.length] = object;
            this.length ++;
        }
    }

    public static void main(String[] args) {
        System.out.println("初始长度10，扩容后15");
        MyArray arr = new MyArray(10);
        arr.push(1);
        for(int i=0;i<10;i++){
            arr.push(i);
        }
        System.out.println("array cap is "+ arr.cap);
        System.out.println("array length is "+ arr.length);
        for(int i=0;i<arr.cap;i++){
            System.out.println(arr.data[i]);
        }
    }
}
